package org.example.forum.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.config.AppConfig;
import org.example.forum.model.Message;
import org.example.forum.model.User;
import org.example.forum.services.IMessageService;
import org.example.forum.services.IUserService;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/message")
@Tag(name = "站内信接口")
public class MessageController {
    @Resource
    private IMessageService messageService;

    @Resource
    private IUserService userService;

    @PostMapping("/send")
    @Operation(summary = "发送站内信")
    public AppResult send(HttpServletRequest request,
                          @Parameter(ref = "接收者id")@RequestParam("receiveUserId")@NonNull Long receiveUserId,
                          @Parameter(ref = "内容")@RequestParam("content")@NonNull String content) {
        //1、校验用户登陆状态，如果禁言就不能发送，报错
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //2、校验发送对象是不是自己（不能给自己发
        if (user.getId() == receiveUserId) {
            return AppResult.failed("不能给自己发送站内信");
        }
        //3、校验接收者是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if (receiveUser == null || receiveUser.getDeleteState() == 1) {
            return AppResult.failed("接收者状态异常！");
        }
        //4、封装对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        //5、调用service
        messageService.create(message);
        //6、返回结果
        return AppResult.success("发送成功");
    }

    @Operation(summary = "获得未读数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        //1、获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //2、调用DAO
        Integer count = messageService.selectUnreadCount(user.getId());
        return AppResult.success(count);
    }

    @Operation(summary = "查询用户的所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        //获取当前登录的用户，并获取用户id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        //返回结果
        return AppResult.success(messages);
    }

    @Operation(summary = "更新站内信状态")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,@Parameter(ref = "站内信id")@RequestParam("id")@NonNull Long id) {
        //1、根据id查询站内信
        Message message = messageService.selectById(id);
        //2、校验站内信是否存在
        if (message == null || message.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //3、站内信是不是自己的
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getId() != message.getReceiveUserId()) {
            //如果不是自己的站内信，就不许访问
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //4、调用service更新状态，把状态更新成已读
        messageService.updateStateById(id, (byte) 1);
        //5、返回结果
        return AppResult.success();
    }

    /**
     *回复站内信
     * @param repliedId 要回复的站内信id
     * @param content 要回复的站内信内容
     * @return
     */
    @Operation(summary = "回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @Parameter(ref = "要回复的站内信id")@RequestParam("repliedId")@NonNull Long repliedId,
                           @Parameter(ref = "要回复的站内信内容")@RequestParam("content")@NonNull String content) {
        //获取当前登录用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //校验要回复的站内信状态
        Message existsMessage = messageService.selectById(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            //站内信不存在
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //不能给自己回复
        if (user.getId() == existsMessage.getPostUserId()) {
            //返回错误
            return AppResult.failed("不能给自己的站内信回复！");
        }
        //构建要更新的对象
        Message message = new Message();
        message.setPostUserId(user.getId()); //发送者
        message.setReceiveUserId(existsMessage.getPostUserId()); //接收者
        message.setContent(content);
        //调用service
        messageService.reply(repliedId,message);
        //返回结果
        return AppResult.success();
    }
}
